package org.jeecg.modules.inOrderPt.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.Inventory.entity.Inventory;
import org.jeecg.modules.Inventory.service.IInventoryService;
import org.jeecg.modules.basicSku.entity.BasicSku;
import org.jeecg.modules.basicSku.service.IBasicSkuService;
import org.jeecg.modules.basicSkuPt.entity.BasicSkuPt;
import org.jeecg.modules.basicSkuPt.service.IBasicSkuPtService;
import org.jeecg.modules.inOrder.entity.InOrder;
import org.jeecg.modules.inOrder.entity.InOrderZi;
import org.jeecg.modules.inOrder.service.IInOrderZiService;
import org.jeecg.modules.inventoryPt.entity.InventoryPt;
import org.jeecg.modules.inventoryPt.service.IInventoryPtService;
import org.jeecg.modules.operationLog.entity.OperationLog;
import org.jeecg.modules.operationLog.service.IOperationLogService;
import org.jeecg.modules.outOrder.service.IOutOrderService;
import org.jeecg.modules.outOrderPt.service.IOutOrderPtService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.inOrderPt.entity.InOrderZiPt;
import org.jeecg.modules.inOrderPt.entity.InOrderPt;
import org.jeecg.modules.inOrderPt.vo.InOrderPtPage;
import org.jeecg.modules.inOrderPt.service.IInOrderPtService;
import org.jeecg.modules.inOrderPt.service.IInOrderZiPtService;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 入库单主表pt品
 * @Author: jeecg-boot
 * @Date: 2024-07-24
 * @Version: V1.0
 */
@Api(tags = "入库单主表pt品")
@RestController
@RequestMapping("/inOrderPt/inOrderPt")
@Slf4j
public class InOrderPtController {
    @Autowired
    private IInOrderPtService inOrderPtService;
    @Autowired
    private IInOrderZiPtService inOrderZiPtService;
    @Autowired
    private IBasicSkuPtService basicSkuPtService;
    @Autowired
    private IInventoryPtService inventoryPtService;
    @Autowired
    private IOperationLogService operationLogService;

    /**
     * 分页列表查询
     *
     * @param inOrderPt
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "入库单主表pt品-分页列表查询")
    @ApiOperation(value = "入库单主表pt品-分页列表查询", notes = "入库单主表pt品-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(InOrderPt inOrderPt,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<InOrderPt> queryWrapper = QueryGenerator.initQueryWrapper(inOrderPt, req.getParameterMap());
        if ((inOrderPt.getNum() != null && !inOrderPt.getNum().isEmpty()) || (inOrderPt.getSkucode() != null && !inOrderPt.getSkucode().isEmpty()) || (inOrderPt.getSkuname() != null && !inOrderPt.getSkuname().isEmpty()) || (inOrderPt.getCustomername() != null && !inOrderPt.getCustomername().isEmpty())) {
            LambdaQueryWrapper<InOrderZiPt> wrapper = new LambdaQueryWrapper<>();
            if ((inOrderPt.getSkucode() != null && !inOrderPt.getSkucode().isEmpty())) {
                wrapper.eq(InOrderZiPt::getSkuCode, inOrderPt.getSkucode());
            }
            if ((inOrderPt.getNum() != null && !inOrderPt.getNum().isEmpty())) {
                wrapper.eq(InOrderZiPt::getNumber, inOrderPt.getNum());
            }
            if ((inOrderPt.getSkuname() != null && !inOrderPt.getSkuname().isEmpty())) {
                wrapper.eq(InOrderZiPt::getSkuName, inOrderPt.getSkuname());
            }
            if ((inOrderPt.getCustomername() != null && !inOrderPt.getCustomername().isEmpty())) {
                wrapper.eq(InOrderZiPt::getCustomerName, inOrderPt.getCustomername());
            }
            List<String> ids = inOrderZiPtService.list(wrapper).stream().map(InOrderZiPt::getInOrderId).collect(Collectors.toList());
            if (ids.isEmpty()) {
                return Result.OK(new Page<InOrder>());
            } else {
                queryWrapper.in("id", ids);
            }
        }
        Page<InOrderPt> page = new Page<InOrderPt>(pageNo, pageSize);
        IPage<InOrderPt> pageList = inOrderPtService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "PT品-入库")
    @ApiOperation(value = "PT品-入库", notes = "PT品-入库")
    @PostMapping("/confirm")
    public Result<?> confirm(@RequestBody InOrderPt inOrderPt) {
        InOrderPt byId = inOrderPtService.getById(inOrderPt.getId());
        if (byId == null) {
            return Result.error("未找到对应数据");
        }
        if (byId.getStatus() == 1) {
            return Result.error("此入库单已入库,请勿重复操作");
        }
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<InOrderZiPt> inOrderZis = inOrderZiPtService.selectByMainId(byId.getId());
        List<InventoryPt> addList = new ArrayList<>();
        List<OperationLog> operationLogs = new ArrayList<>();
        for (InOrderZiPt inOrderZi : inOrderZis) {
            inOrderZi.setInTime(inOrderZi.getInTime() == null ? byId.getInTime() : inOrderZi.getInTime());
            inOrderZi.setInventory(inOrderZi.getNumber());
            inOrderZi.setStatus(0);
            String skuCode = inOrderZi.getSkuCode();
            String location = inOrderZi.getLocation();
            OperationLog operationLog = new OperationLog();
            InventoryPt inventory = new InventoryPt();
            BeanUtils.copyProperties(inOrderZi, inventory);
            inventory.setId(null).setCreateBy(null).setCreateTime(null).setUpdateBy(null).setUpdateTime(null);
            addList.add(inventory);
            operationLog.setNewNumber(inOrderZi.getNumber());
            operationLog.setSkuCode(skuCode).setSkuName(inOrderZi.getSkuName()).setNumber(inOrderZi.getNumber())
                    .setOperationTime(new Date()).setOperationType("入库").setOperator(user.getRealname())
                    .setLocation(location).setInTime(inOrderZi.getInTime());
            operationLogs.add(operationLog);
        }
        inventoryPtService.saveBatch(addList);
        byId.setStatus(1);
        byId.setRealname(user.getRealname());
        inOrderPtService.updateById(byId);
        inOrderZiPtService.updateBatchById(inOrderZis);
        operationLogService.saveBatch(operationLogs);
        return Result.OK("入库成功", null);
    }

    @PostMapping("/getBoxNum")
    public Result<?> getBoxNum(@RequestBody JSONObject jsonObject) {
        String number = jsonObject.getString("number");
        String skuCode = jsonObject.getString("skuCode");
        String customerSkuCode = jsonObject.getString("customerSkuCode");
        BigDecimal numberBigDeimal = new BigDecimal(number);
        if (customerSkuCode != null && !customerSkuCode.isEmpty()) {
            BasicSkuPt one = basicSkuPtService.list(new LambdaQueryWrapper<BasicSkuPt>().eq(BasicSkuPt::getCustomerSkuCode, customerSkuCode)).get(0);
            if (one != null) {
                BigDecimal specificationsNumBigDeimal = new BigDecimal(one.getSpecificationsNum().toString());
                BigDecimal divide = numberBigDeimal.divide(specificationsNumBigDeimal, 2, RoundingMode.HALF_UP);
                return Result.OK(divide);
            }
        } else if (skuCode != null && !skuCode.isEmpty()) {
            BasicSkuPt one = basicSkuPtService.list(new LambdaQueryWrapper<BasicSkuPt>().eq(BasicSkuPt::getSkuCode, skuCode)).get(0);
            if (one != null) {
                BigDecimal specificationsNumBigDeimal = new BigDecimal(one.getSpecificationsNum().toString());
                BigDecimal divide = numberBigDeimal.divide(specificationsNumBigDeimal, 2, RoundingMode.HALF_UP);
                return Result.OK(divide);
            }
        }
        return Result.error("");
    }

    /**
     *   添加
     *
     * @param inOrderPtPage
     * @return
     */
    @AutoLog(value = "入库单主表pt品-添加")
    @ApiOperation(value = "入库单主表pt品-添加", notes = "入库单主表pt品-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody InOrderPtPage inOrderPtPage) {
        List<BasicSkuPt> skus = basicSkuPtService.list();
        Set<String> collect = skus.stream().map(BasicSkuPt::getSkuCode).collect(Collectors.toSet());
        Result<Object> error = getResult(inOrderPtPage.getInOrderZiPtList(), collect);
        if (error != null) return error;
        InOrderPt inOrderPt = new InOrderPt();
        BeanUtils.copyProperties(inOrderPtPage, inOrderPt);
        // 封装子表长宽高体积
        inOrderPtPage.getInOrderZiPtList().stream().forEach(data->{
            String skuCode = data.getSkuCode();
            List<BasicSkuPt> list = basicSkuPtService.list(new QueryWrapper<BasicSkuPt>().eq("sku_code", skuCode));
            BasicSkuPt basicSkuPt = list.stream().filter(a -> a.getLength() != null && a.getWidth() != null && a.getHeight() != null).collect(Collectors.toList()).get(0);
            data.setLength(basicSkuPt.getLength());
            data.setWidth(basicSkuPt.getWidth());
            data.setHeight(basicSkuPt.getHeight());
            data.setVolume(data.getLength().multiply(data.getWidth()).multiply(data.getHeight()).setScale(2,BigDecimal.ROUND_HALF_UP));
        });

        inOrderPtService.saveMain(inOrderPt, inOrderPtPage.getInOrderZiPtList());
        return Result.OK("添加成功！");
    }

    private static @Nullable Result<Object> getResult(List<InOrderZiPt> inOrderZiList, Set<String> collect) {
        for (InOrderZiPt inOrderZi : inOrderZiList) {
            String sku = inOrderZi.getSkuCode().replaceAll(" ", "");
            String location = inOrderZi.getLocation().replaceAll(" ", "");
            inOrderZi.setSkuCode(sku);
            inOrderZi.setLocation(location);
            if (!collect.contains(sku)) {
                return Result.error("入库单中【" + inOrderZi.getSkuCode() + "】品番不存在,若确认无误，请先维护品番数据");
            }
        }
        return null;
    }

    /**
     *  编辑
     *
     * @param inOrderPtPage
     * @return
     */
    @AutoLog(value = "入库单主表pt品-编辑")
    @ApiOperation(value = "入库单主表pt品-编辑", notes = "入库单主表pt品-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody InOrderPtPage inOrderPtPage) {
        InOrderPt inOrderPt = new InOrderPt();
        BeanUtils.copyProperties(inOrderPtPage, inOrderPt);
        InOrderPt inOrderPtEntity = inOrderPtService.getById(inOrderPt.getId());
        if (inOrderPtEntity == null) {
            return Result.error("未找到对应数据");
        }
        inOrderPtService.updateMain(inOrderPt, inOrderPtPage.getInOrderZiPtList());
        return Result.OK("编辑成功!");
    }

    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库单主表pt品-通过id删除")
    @ApiOperation(value = "入库单主表pt品-通过id删除", notes = "入库单主表pt品-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        inOrderPtService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     *  批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "入库单主表pt品-批量删除")
    @ApiOperation(value = "入库单主表pt品-批量删除", notes = "入库单主表pt品-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.inOrderPtService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库单主表pt品-通过id查询")
    @ApiOperation(value = "入库单主表pt品-通过id查询", notes = "入库单主表pt品-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        InOrderPt inOrderPt = inOrderPtService.getById(id);
        if (inOrderPt == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(inOrderPt);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库单PT品子表通过主表ID查询")
    @ApiOperation(value = "入库单PT品子表主表ID查询", notes = "入库单PT品子表-通主表ID查询")
    @GetMapping(value = "/queryInOrderZiPtByMainId")
    public Result<?> queryInOrderZiPtListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<InOrderZiPt> inOrderZiPtList = inOrderZiPtService.selectByMainId(id);
        return Result.OK(inOrderZiPtList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param inOrderPt
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, InOrderPt inOrderPt) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<InOrderPt> queryWrapper = QueryGenerator.initQueryWrapper(inOrderPt, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<InOrderPt> queryList = inOrderPtService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<InOrderPt> inOrderPtList = new ArrayList<InOrderPt>();
        if (oConvertUtils.isEmpty(selections)) {
            inOrderPtList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            inOrderPtList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<InOrderPtPage> pageList = new ArrayList<InOrderPtPage>();
        for (InOrderPt main : inOrderPtList) {
            InOrderPtPage vo = new InOrderPtPage();
            BeanUtils.copyProperties(main, vo);
            List<InOrderZiPt> inOrderZiPtList = inOrderZiPtService.selectByMainId(main.getId());
            vo.setInOrderZiPtList(inOrderZiPtList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "入库单主表pt品列表");
        mv.addObject(NormalExcelConstants.CLASS, InOrderPtPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("入库单主表pt品数据", "导出人:" + sysUser.getRealname(), "入库单主表pt品"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<InOrderPtPage> list = ExcelImportUtil.importExcel(file.getInputStream(), InOrderPtPage.class, params);
                for (InOrderPtPage page : list) {
                    InOrderPt po = new InOrderPt();
                    BeanUtils.copyProperties(page, po);
                    po.setInTime(po.getInTime() == null ? new Date() : po.getInTime());
                    inOrderPtService.saveMain(po, page.getInOrderZiPtList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
